package com.cdck.safe.dete.controller;

import com.cdck.safe.dete.common.result.Result;
import com.cdck.safe.dete.common.util.FileUtil;
import com.cdck.safe.dete.model.dto.FileInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

/**
 * @author xiaozhu
 * @date 2024/2/27 9:11
 */
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileController {

    @Value("${file.pfx.image}")
    private String resourceFilePath;

    /**
     * 上传文件
     * @param file 文件
     * @return FileInfo
     */
    @PostMapping("/uploadImage")
    public Result<FileInfo> uploadImageFile(@RequestPart("file") MultipartFile file) {
        String pfx = "/dev-api/api/v1/files/image/";
        FileInfo fileInfo = FileUtil.uploadImageFile(file, resourceFilePath, pfx);
        return Result.success(fileInfo);
    }

    /**
     * 获取图片文件数据
     * @param fileName 文件名
     */
    @GetMapping("/image/{fileName}")
    public void  imageShow(@PathVariable("fileName" )  String  fileName, HttpServletResponse response) {
        String fileURL = resourceFilePath + "image/" + fileName;
        InputStream inputStream = null;
        try {
            File file = new File(fileURL);
            if (!file.exists()){
                return;
            }
            inputStream = Files.newInputStream(file.toPath());
            int i = inputStream.available();
            //byte数组用于存放图片字节数据
            byte[] buff = new byte[i];
            inputStream.read(buff);
            //关闭输入流
            inputStream.close();
            //设置发送到客户端的响应内容类型
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            OutputStream out = response.getOutputStream();
            out.write(buff);
            //关闭响应输出流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
